package sfeir.ergosum.myprofile;

import sfeir.ergosum.MyProfileActivity;
import sfeir.ergosum.R;
import sfeir.ergosum.menu.MenuService;
import sfeir.ergosum.model.Address;
import sfeir.ergosum.model.Contact;
import sfeir.ergosum.model.Email;
import sfeir.ergosum.model.NetworkItem;
import sfeir.ergosum.model.Person;
import sfeir.ergosum.model.Tel;
import sfeir.ergosum.model.spreadsheet.SpreadsheetEntry;
import sfeir.ergosum.tools.SpreadsheetClient;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;

public class NewProfileActivity extends Activity {

    private static final int DIALOG_BIRTHDAY = 0;
    private SharedPreferences mPrefs;
    private ProgressDialog mProgress;
    private SpreadsheetClient mSpreadsheetClient = new SpreadsheetClient(
            new SpreadsheetClient.ResponseHandler() {
                @Override
                public void handleMessage(Message msg) {
                    if (mFinished)
                        return;
                    switch (msg.what) {
                    case R.id.httpclient_ready:
                        mProgress.setMessage(getString(R.string.authenticating));
                        mProgress.setProgress(1000);
                        String ids = mPrefs.getString(
                                "preference_loginpassKey", " \n ");
                        String[] values = new String[2];
                        values = ids.split("\n");
                        mSpreadsheetClient.setUserCredentials(values[0],
                                values[1]);
                        mSpreadsheetClient.handler.obtainMessage(
                                R.id.request_login, R.id.client_auth_writely,
                                0, "writely").sendToTarget();
                        break;
                    case R.id.client_auth_writely:
                        mProgress.setMessage(getString(R.string.profile_new_sending));
                        mProgress.setProgress(6000);
                        if (null != mContact)
                            mSpreadsheetClient.handler.obtainMessage(
                                    R.id.request_update_spreadsheet,
                                    mContact.getUrl() + "\n" + buildCSV())
                                    .sendToTarget();
                        else
                            mSpreadsheetClient.handler.obtainMessage(
                                    R.id.request_new_spreadsheet, buildCSV())
                                    .sendToTarget();
                        break;
                    case R.id.client_updated_spreadsheet:
                        Toast.makeText(NewProfileActivity.this,
                                "Profile updated.", 3000);
                        SpreadsheetEntry updatedEntry = (SpreadsheetEntry) msg.obj;
                        String ekey = updatedEntry.getId();
                        ekey = ekey.substring(ekey
                                .lastIndexOf("spreadsheet%3A") + 14);

                        Intent intent = new Intent(NewProfileActivity.this, MyProfileActivity.class);
                        intent.putExtra("key", ekey);
                        startActivityForResult(intent, MenuService.REFRESH);

                        mSpreadsheetClient.terminate();
                        mSpreadsheetClient = null;
                        finish();
                        break;
                    case R.id.client_new_spreadsheet:
                        Toast.makeText(NewProfileActivity.this,
                                "Profile created.", 3000);
                        SpreadsheetEntry entry = (SpreadsheetEntry) msg.obj;
                        String key = entry.getId();
                        key = key
                                .substring(key.lastIndexOf("spreadsheet%3A") + 14);
                        mPrefs.edit().putString("profile_spreadsheet_key", key)
                                .commit();
                        mProgress.setMessage("Sharing with the world");
                        mSpreadsheetClient.handler.obtainMessage(
                                R.id.request_share_world, key).sendToTarget();
                        break;
                    case R.id.client_shared_world:
                        mProgress.dismiss();
                        MenuService.startProfileDetailsActivity(
                                NewProfileActivity.this, (String) msg.obj);

                        mSpreadsheetClient.terminate();
                        mSpreadsheetClient = null;
                        finish();
                        break;
                    default:
                        super.handleMessage(msg);
                        break;
                    }
                }
            });

    private boolean mFinished;
    private Button mBirthdayButton;
    private Button mCreateButton;
    private Contact mContact;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.newprofile);

        mContact = (Contact) getIntent().getSerializableExtra("contact");

        mBirthdayButton = (Button) findViewById(R.id.btBirthDay);
        mCreateButton = (Button) findViewById(R.id.btCreateProfile);
        if (null != mContact) {
            fillProfile();
            mCreateButton.setText("Update");
        }

        mBirthdayButton.setOnClickListener(new BirthdayClickListener());
        mCreateButton.setOnClickListener(new CreateClickListener());

        mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    }

    private void setText(int id, String value) {
        TextView tv = (TextView) findViewById(id);
        tv.setText(value);
    }

    private void fillProfile() {
        Person p = mContact.getPerson();
        setText(R.id.etAboutMe, p.getAboutMe());
        for (Address address : p.getAddresses()) {
            switch (address.getType()) {
            case Address.PERSONAL_ADDRESS:
                setText(R.id.etAddressPerso, address.toString());
                break;
            case Address.PROFESSIONNAL_ADDRESS:
                setText(R.id.etAddressPro, address.toString());
            default:
                break;
            }
        }
        setText(R.id.etCompany, p.getCompany());
        for (Email email : p.getEmails()) {
            switch (email.getTypeEmail()) {
            case Email.PERSONAL_EMAIL:
                setText(R.id.etEmailPerso, email.getEmail());
                break;
            case Email.PROFESSIONNAL_EMAIL:
                setText(R.id.etEmailPro, email.getEmail());
            default:
                break;
            }
        }
        for (NetworkItem item : p.getNetworkItems()) {
            if ("facebook".equals(item.getNetworkItemType())) {
                setText(R.id.etFacebookID, item.getNetworkItemLink());
            } else if ("twitter".equals(item.getNetworkItemType())) {
                setText(R.id.etTwitterAccount, item.getNetworkItemLink());
            } else if ("linkedin".equals(item.getNetworkItemType())) {
                setText(R.id.etLinkedIn, item.getNetworkItemLink());
            } else if ("viadeo".equals(item.getNetworkItemType())) {
                setText(R.id.etViadeoAccount, item.getNetworkItemLink());
            }
        }
        setText(R.id.etFirstName, p.getFirstname());
        setText(R.id.etLastName, p.getName());
        setText(R.id.etNickName, p.getNickname());
        setText(R.id.etPhotoURL, p.getPhoto().getImageUrl());
        for (Tel tel : p.getTels()) {
            switch (tel.getType()) {
            case Tel.HOME_LANDLINE:
                setText(R.id.etTelPerso, tel.getPhoneNumber());
                break;
            case Tel.PROFESSIONNAL_LINE:
                setText(R.id.etTelPro, tel.getPhoneNumber());
                break;
            default:
                break;
            }
        }
        setText(R.id.etTitle, p.getTitle());
    }

    protected String buildCSV() {
        return new CSVBuilder().append("lastname", R.id.etLastName).append(
                "firstname", R.id.etFirstName).append("nickname",
                R.id.etNickName).append("birthday", R.id.btBirthDay).append(
                "title", R.id.etTitle).append("company", R.id.etCompany)
                .append("aboutMe", R.id.etAboutMe).append("picture",
                        R.id.etPhotoURL).append("email_pro", R.id.etEmailPro)
                .append("email_perso", R.id.etEmailPerso).append("adress_pro",
                        R.id.etAddressPro).append("adress_perso",
                        R.id.etAddressPerso).append("tel_pro", R.id.etTelPro)
                .append("tel_perso", R.id.etTelPerso).append("facebook",
                        R.id.etFacebookID).append("twitter",
                        R.id.etTwitterAccount).append("linkedin",
                        R.id.etLinkedIn).append("viadeo", R.id.etViadeoAccount)
                .toString();
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_BIRTHDAY:
            return new DatePickerDialog(this,
                    new DatePickerDialog.OnDateSetListener() {

                        @Override
                        public void onDateSet(DatePicker view, int year,
                                int monthOfYear, int dayOfMonth) {
                            // TODO use date formatter
                            mBirthdayButton
                                    .setText(((dayOfMonth > 9) ? dayOfMonth
                                            : ("0" + dayOfMonth))
                                            + "/"
                                            + ((monthOfYear > 9) ? (monthOfYear + 1)
                                                    : ("0" + (monthOfYear + 1)))
                                            + "/" + year);
                        }

                    }, 1980, 07, 15);
        }
        return null;
    }

    private class BirthdayClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            showDialog(DIALOG_BIRTHDAY);
        }
    }

    private class CreateClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            if (null != mSpreadsheetClient && !mSpreadsheetClient.isAlive())
                mSpreadsheetClient.start();
            mProgress = ProgressDialog.show(NewProfileActivity.this,
                    getString(R.string.profile_creating), "", false, true,
                    new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            if (null != mSpreadsheetClient
                                    && mSpreadsheetClient.isAlive())
                                mSpreadsheetClient.terminate();
                            finish();
                        }
                    });
        }
    }

    private class CSVBuilder {
        private StringBuilder mStringBuilder = new StringBuilder();

        public CSVBuilder() {
            mStringBuilder.append("param,val");
        }

        public CSVBuilder append(String param, int id) {
            CharSequence textViewText = ((TextView) findViewById(id)).getText();
            mStringBuilder.append("\n" + param);
            if (null != textViewText && 0 < textViewText.length())
                mStringBuilder.append("," + textViewText);
            return this;
        }

        @Override
        public String toString() {
            return mStringBuilder.toString();
        }
    }
}
